package com.auto;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.system.auth.AuthUtil;
import com.system.comm.utils.FrameHttpUtil;
import com.system.comm.utils.FrameJsonUtil;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;

public class MonitorUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MonitorUtil.class);

	public static ResponseFrame post(String url, Map<String, Object> params) {
		ResponseFrame frame = null;
		String time = String.valueOf(System.currentTimeMillis());
		String sercret = AutoConfig.clientToken;
		params.put("clientId", AutoConfig.clientId);
		params.put("time", time);
		params.put("sign", AuthUtil.auth(AutoConfig.clientId, time, sercret));
		try {
			String result = FrameHttpUtil.post(getHost() + url, params);
			frame = FrameJsonUtil.toObject(result, ResponseFrame.class);
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
			return new ResponseFrame(ResponseCode.SERVER_ERROR);
		}
		return frame;
	}

	private static String getHost() {
		String host = AutoConfig.monitorHost;
		return host;
	}

	/**
	 * 上传文件
	 * @param filePath
	 * @param type		10部署项目的文件
	 * @return
	 */
	public static ResponseFrame sysFileUpload(String filePath, Integer type) {
		ResponseFrame frame = new ResponseFrame();
		File file = new File(filePath);
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httppost = new HttpPost(getHost() + "/api/sysFile/upload");
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
			httppost.setConfig(requestConfig);
			String clientIdString = AutoConfig.clientId;
			String sercret = AutoConfig.clientToken;
			String timeString = String.valueOf(System.currentTimeMillis());
			FileBody bin = new FileBody(file);
			//设置传输参数,设置编码。设置浏览器兼容模式，解决文件名乱码问题
			StringBody clientId = new StringBody(clientIdString, ContentType.TEXT_PLAIN);
			StringBody time = new StringBody(timeString, ContentType.TEXT_PLAIN);
			StringBody sign = new StringBody(AuthUtil.auth(clientIdString, timeString, sercret), ContentType.TEXT_PLAIN);
			HttpEntity reqEntity = MultipartEntityBuilder.create()
					.setCharset(Charset.forName("UTF-8"))
					.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
					.addPart("file", bin)
					.addPart("clientId", clientId)
					.addPart("time", time)
					.addPart("sign", sign)
					.addPart("filename", new StringBody("file", ContentType.TEXT_PLAIN))
					.addPart("type", new StringBody(String.valueOf(type), ContentType.TEXT_PLAIN))
					//.addPart("typeSecond", new StringBody(FrameStringUtil.isEmpty(typeSecond) ? "" : typeSecond, ContentType.TEXT_PLAIN))
					.build();
			httppost.setEntity(reqEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					String responseEntityStr = EntityUtils.toString(response.getEntity());
					//LOGGER.info("上传文件返回内容: " + responseEntityStr);
					frame = FrameJsonUtil.toObject(responseEntityStr, ResponseFrame.class);
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			LOGGER.error(e.getMessage(), e);
			frame.setCode(ResponseCode.SERVER_ERROR.getCode());
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
			frame.setCode(ResponseCode.SERVER_ERROR.getCode());
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				LOGGER.error(e.getMessage(), e);
			}
		}
		return frame;
	}
	/**
	 * 部署项目
	 * @param appcode
	 * @param username
	 * @param version
	 * @param remark
	 * @param clients	多个,分隔
	 * @param logpath
	 * @param url 
	 * @return
	 */
	public static ResponseFrame prjVersionDeploy(String appcode, String username, String version, String remark,
			String clients, String logpath, String url) {
		Map<String, Object> params = new HashMap<>();
		params.put("appcode", appcode);
		params.put("username", username);
		params.put("version", version);
		params.put("remark", remark);
		params.put("clients", clients);
		params.put("logpath", logpath);
		params.put("url", url);
		ResponseFrame frame = post("/api/prjVersion/deploy", params);
		return frame;
	}
}